Imports System.Data.SqlClient

Public Class DataBrowseDemo

    Private Function GetDataTable(ByVal DataBaseName As String, ByVal SqlStr As String) As DataTable
        Dim Username As String = "sa"
        Dim Password As String = ""
        Dim conn As New SqlConnection()
        conn.ConnectionString = String.Format("user id={0};pwd={1};data source=.;initial catalog={2}", Username, Password, DatabaseName)

        Dim da As New SqlDataAdapter(SqlStr, conn)
        Dim table As New DataTable
        da.Fill(table)
        Return table
    End Function
    Private Sub DataBrowseDemo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TreeView1.ImageList = Me.ImageList1
        ListView1.SmallImageList = Me.ImageList1

        Me.ListView1.Columns.Add("Table Name", 120, HorizontalAlignment.Right)
        Me.ListView1.Columns.Add("Date", 200, HorizontalAlignment.Right)
        ListView1.FullRowSelect = True
        ListView1.View = View.Details

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Database
        Dim table As DataTable = GetDataTable("master", "SELECT Name FROM sysdatabases")
        For i As Integer = 0 To table.Rows.Count - 1
            Dim n As TreeNode = TreeView1.Nodes.Add(table.Rows(i)("Name"))            
            n.SelectedImageIndex = 4
            n.ImageIndex = 4
        Next
    End Sub

    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        Dim DatabaseName As String = e.Node.Text
        Dim sqlStr As String = "SELECT NAME,CRDATE FROM SYSOBJECTS WHERE TYPE='U'"
        Dim table As DataTable = GetDataTable(DatabaseName, sqlStr)


        ListView1.Items.Clear()
        Dim item As ListViewItem
        For i As Integer = 0 To table.Rows.Count - 1
            Dim tableName As String = table.Rows(i)("NAME")
            Dim createDate As String = table.Rows(i)("CRDATE")

            item = New ListViewItem(tableName)
            item.SubItems.Add(createDate)
            item.ImageIndex = 1

            ListView1.Items.Add(item)
        Next

    End Sub

    Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
        Dim DatabaseName As String = TreeView1.SelectedNode.Text
        Dim tableName As String = ListView1.SelectedItems(0).Text
        Dim sqlStr As String = String.Format("SELECT * FROM ""{0}""", tableName)
        Dim table As DataTable = GetDataTable(DatabaseName, sqlStr)
        
        Dim F As New Form
        F.Text = String.Format("Database {0} : {1}", DatabaseName, tableName)
        Dim gridView As New DataGridView
        gridView.Dock = DockStyle.Fill
        gridView.DataSource = table
        F.Controls.Add(gridView)
        F.Show()



    End Sub

    
End Class
